pub mod user;
pub mod post;

mod form {
    use serde::Deserialize;
    use validator::Validate;

    #[derive(Deserialize, Validate)]
    pub struct PagerForm {
        pub page: u64,
        #[validate(range(min = 5, max = 20))]
        pub limit: u64
    }
}

mod resp {
    use actix_web::{ResponseError, HttpResponse, web::Json};
    use serde_json::{json, Value};

    #[derive(Debug)]
    pub struct Error {
        message: String
    }

    impl Error {
        pub fn new(message: impl Into<String>) -> Self {
            Self { message: message.into() }
        }
    }

    impl <T: std::error::Error> From<T> for Error {
        fn from(e: T) -> Self {
            Self::new(format!("System error: {e}"))
        }
    }

    impl std::fmt::Display for Error {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.message)
        }
    }

    impl ResponseError for Error {
        fn error_response(&self) -> HttpResponse {
            HttpResponse::Ok().json(json!({
                "success": false,
                "message": self.message
            }))
        }
    }

    pub type Result = std::result::Result<Json<Value>, Error>;

    pub fn ok(data: Value) -> Result {
        Ok(Json(json!({
            "success": true,
            "data": data
        })))
    }

    pub fn err(message: impl Into<String>) -> Result {
        Err(Error::new(message))
    }
}
